<?php

namespace catchAdmin\pc\model;

use catchAdmin\model\Notice;
use catchAdmin\model\UserCompanyStatusLog;
use catchAdmin\model\WechatUser;
use catcher\exceptions\AlertErrorException;

class UserExt extends \catchAdmin\model\UserExt
{

    public $name = 'UserExt';


    public function indexData($param)
    {
        $app = $this;

        return $this->indexDataPcCC($param, $app);
    }


    /**
     * 审核
     */
    public function audit($param)
    {
        $user_ext_msg = $this
            ->where('id', $param['id'])
            ->find();
        if ($user_ext_msg->company_status != 2) {
            throw new AlertErrorException('不能重复审核');
        }

        $this->startTrans();

        // 1.更新公司表，并记日志
        {
            $user_ext_msg = $this->saveDataCC([
                'id'                  => $user_ext_msg->id,
                'audit_time'          => time(),
                'company_status'      => $param['company_status'],
                'company_status_note' => $param['company_status_note'] ?? '',
            ]);
            (new UserCompanyStatusLog())->saveDataCC([
                'user_id'             => $param['creator_id'],
                'wechat_user_id'      => $user_ext_msg['wechat_user_id'],
                'user_ext_id'         => $user_ext_msg['id'],
                'status_no'           => $user_ext_msg['status_no'],
                'company_status'      => $user_ext_msg['company_status'],
                'company_status_note' => $user_ext_msg['company_status_note'],
            ]);
        }

        // 2.更新用户表审核状态
        {
            $wechat_user_msg = (new \catchAdmin\model\WechatUser())->saveDataCC([
                'id'             => $user_ext_msg['wechat_user_id'],
                'company_status' => $user_ext_msg['company_status'],
                'company_name'   => $user_ext_msg['realname'],
            ]);

            if ($user_ext_msg['company_status'] == 3) {
                $share_code = $wechat_user_msg->share_code;
                if (empty($share_code)) {
                    $share_code = (new WechatUser())->getShareCode();
                    $wechat_user_msg->share_code = $share_code;
                }
                $wechat_user_msg->share_img = (new \catchAdmin\model\WechatUser())->getShareImg($wechat_user_msg->id, $share_code);
                $wechat_user_msg->save();
            }
        }

        // 3.发消息
        (new Notice())->saveDataCC([
            // 个人认证——审核结果
            'notice_type'    => 4,
            'title'          => $user_ext_msg['company_status_name'],
            'content'        => $user_ext_msg['company_status_note'],
            'wechat_user_id' => $user_ext_msg['wechat_user_id'],
        ]);

        $this->commit();

        return true;
    }
}
